package com.jfire.socket.socketserver.handler.impl;

import java.nio.charset.Charset;
import javax.annotation.Resource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.jfire.baseutil.collection.ByteCache;
import com.jfire.json.JsonArray;
import com.jfire.json.JsonObject;
import com.jfire.socket.socketserver.bus.BusinessCommand;
import com.jfire.socket.socketserver.bus.Message;
import com.jfire.socket.socketserver.bus.MessageHandlerCenter;
import com.jfire.socket.socketserver.handler.MessageHandler;
import com.jfire.socket.socketserver.interceptor.MessageInterceptor;

@Resource
public class ServerInfoHandler implements MessageHandler
{
    private Logger               logger  = LogManager.getLogger();
    private Charset              charset = Charset.forName("utf8");
    @Resource
    private MessageHandlerCenter requestHandlerCenter;
    
    @Override
    public byte interestedDataPacketType()
    {
        return BusinessCommand.SERVER_INFO;
    }
    
    @Override
    public void handler(Message message)
    {
        ByteCache cache = message.getBusinessData();
        String command = cache.toString(charset);
        JsonObject jsonObject = new JsonObject();
        switch (command)
        {
            case "all":
                jsonObject.put("handlers", getHandlerNames());
                jsonObject.put("interceptors", getInterceptorNames());
                logger.info(jsonObject.toString());
                break;
            case "handler":
                jsonObject.put("handlers", getHandlerNames());
                break;
            case "interceptor":
                jsonObject.put("interceptors", getInterceptorNames());
                break;
            default:
                break;
        }
        cache.clear().putArray(jsonObject.toString().getBytes(charset));
        cache.startRead(0);
    }
    
    private JsonArray getHandlerNames()
    {
        JsonArray jsonArray = new JsonArray();
        for (MessageHandler handler : requestHandlerCenter.getHandlerList())
        {
            jsonArray.add(handler.getClass().getName());
        }
        return jsonArray;
    }
    
    private JsonArray getInterceptorNames()
    {
        JsonArray jsonArray = new JsonArray();
        for (MessageInterceptor interceptor : requestHandlerCenter.getInterceptorList())
        {
            jsonArray.add(interceptor.getClass().getName());
        }
        return jsonArray;
    }
}
